(function() {
  var themes = {
    'grass': {
      'name': 'Grass',
      'urlId': 'Grass'
    },
    'classic': {
      'name': 'Classic',
      'urlId': 'default',
      'installedName': 'Default'
    },
    'baseball': {
      'name': 'Baseball',
      'urlId': 'Baseball'
    },
    'brushed': {
      'name': 'Brushed',
      'urlId': 'Brushed'
    },
    'candy': {
      'name': 'Candy',
      'urlId': 'Candy'
    },
    'colorchips': {
      'name': 'Color Chips',
      'urlId': 'ColorChips'
    },
    'corkboard': {
      'name': 'Cork Board',
      'urlId': 'CorkBoard'
    },
    'desktop': {
      'name': 'Desktop',
      'urlId': 'Desktop'
    },
    'dots': {
      'name': 'Dots',
      'urlId': 'Dots'
    },
    'earthy': {
      'name': 'Earthy',
      'urlId': 'Earthy'
    },
    'floralblue': {
      'name': 'Floral Blue',
      'urlId': 'BlueFloral',
      'installedName': 'Blue Floral'
    },
    'folders': {
      'name': 'Folders',
      'urlId': 'Manilla',
      'installedName': 'Manilla'
    },
    'glossyblue': {
      'name': 'Glossy Blue',
      'urlId': 'GlossBlue'
    },
    'glow': {
      'name': 'Glow',
      'urlId': 'Glow'
    },
    'gradient': {
      'name': 'Gradient',
      'urlId': 'Gradient'
    },
    'greyscale': {
      'name': 'Greyscale',
      'urlId': 'Greyscale'
    },
    'horizontalstripe': {
      'name': 'Horizontal Stripe',
      'urlId': 'HorizontalStripes',
      'installedName': 'Horizontal Stripes'
    },
    'latenight': {
      'name': 'Late Night',
      'urlId': 'LateNight'
    },
    'legalpad': {
      'name': 'Legal Pad',
      'urlId': 'Legal',
      'installedName': 'Legal'
    },
    'marble': {
      'name': 'Marble',
      'urlId': 'Marble'
    },
    'minimal': {
      'name': 'Minimal',
      'urlId': 'Minimal'
    },
    'pencilsketch': {
      'name': 'Pencil Sketch',
      'urlId': 'PencilSketch'
    },
    'quilt': {
      'name': 'Quilt',
      'urlId': 'Quilt'
    },
    'stargazing': {
      'name': 'Star Gazer',
      'urlId': 'StarGazing',
      'installedName': 'Star Gazing'
    },
    'stitches': {
      'name': 'Stitches',
      'urlId': 'Stitches'
    },
    'topography': {
      'name': 'Topography',
      'urlId': 'Topography'
    },
    'transparent': {
      'name': 'Transparent',
      'urlId': 'Transparent'
    },
    'verticalstripe': {
      'name': 'Vertical Stripe',
      'urlId': 'VStripe',
      'installedName': 'VStripe'
    },
    'zenspring': {
      'name': 'Zen Spring',
      'urlId': 'ZenSpring'
    }
  };
  var initThemes = ['brushed', 'candy', 'desktop', 'earthy', 'folders',
    'glossyblue', 'gradient', 'greyscale', 'latenight', 'legalpad', 'minimal'];
  var $changeThemeBtn = $('#change-theme');
  var $thumbnail = $('#thumbnail-of-theme');
  var $themeChangeWrapper = $('#theme-change-wrapper');
  var $themeSelectionArea = $('#theme-selection-area');
  var $themeSelectionBtn = $('#theme-selection-btn');
  
  var st = window.ShortcutTheme = {
    setup: function() {
      $changeThemeBtn.on('click', st.showThemeChangeWrapper);
      $('#theme-selection-cancel-btn').on('click', st.hideThemeChangeWrapper);

      // Set selected theme.
      $themeSelectionBtn.on('click', function() {
        var $selectedTheme = $('.theme-selected', $themeSelectionArea);
        var themeId = $selectedTheme.attr('data-theme-id');
        var themeUrlId = themes[themeId].urlId;
        var themeUrl = st.constructThemeUrl(themeUrlId);
        var themeData = {
          id: themeId,
          url: themeUrl,
          imageSrc: $('img', $selectedTheme).attr('src'),
          title: themes[themeId].name
        };
        st.setThemeData(themeData);
        st.hideThemeChangeWrapper();
      });

      $themeSelectionArea.on('click', function(e) {
        var target = e.target;
        if (target.tagName == 'LI') {
          st.selectTheme(target);
        } else if (target.tagName == 'IMG' || target.tagName == 'LABEL') {
          st.selectTheme(target.parentNode);
        }
      });

      st.constructThemeSelectionHtml();
    },

    constructThemeSelectionHtml: function() {
      for (var themeId in themes) {
        var theme = themes[themeId];
        var themeName = theme.name;
        var imgUrl = st.constructThemeImgUrl(themeId);
        var img = document.createElement('img');
        $(img).attr('src', imgUrl).attr('alt', themeId);
        var label = document.createElement('label');
        $(label).text(themeName);
        var li = document.createElement('li');
        $(li).attr('data-theme-id', themeId).append(img).append(label);
        $themeSelectionArea.append(li);
      }

      // Reorder themes, and put the classic theme at the first place.
      $('li', $themeSelectionArea).each(function(theme) {
        var themeId = $(theme).attr('data-theme-id');
        if (initThemes.indexOf(themeId) < 0 && themeId != 'classic') {
          $themeSelectionArea.append(theme);
        }
      });
    },
    
    init: function() {
      var themeIndex = Math.random() * (initThemes.length + 1) | 0;
      var themeId = initThemes[themeIndex];
      var $theme = $('[data-theme-id="' + themeId + '"]', $themeSelectionArea);
      $theme.trigger('click');
      $themeSelectionBtn.trigger('click');
    },

    constructThemeUrl: function(urlId) {
      return 'https://dl-ssl.google.com/chrome/extensions/' + urlId + '.crx';
    },

    constructThemeImgUrl: function(themeId) {
      if (themeId == 'custom') {
        var currentLocale = Manager.currentLocale;
        if (currentLocale.indexOf('en') == 0) {
          currentLocale = 'en';
        }
        themeId = themeId + '_' + currentLocale;
      }
      return 'images/theme_thumbs/thumb_' + themeId + '_sm.jpg';
    },
    
    showThemeChangeWrapper: function() {
      $.setDialogPosition($themeChangeWrapper.get());
      $themeChangeWrapper.show();
      Manager.showOverlay();
      st.selectInvertTheme();
    },
    
    hideThemeChangeWrapper: function() {
      $themeChangeWrapper.hide();
      Manager.hideOverlay();
    },

    getThemeData: function() {
      var themeId = $thumbnail.attr('data-theme-id');
      var themeName = $thumbnail.attr('title');
      var themeUrl = $thumbnail.attr('data-theme-url');
      return {
        id: themeId,
        name: themeName,
        url: themeUrl
      };
    },

    /**
     * Set data values for selected theme: theme id, theme name, theme img and
     * full theme url.
     * @param {Object} theme
     *   required keys: id, url, imageSrc, title
     */
    setThemeData: function(theme) {
      $thumbnail.attr('data-theme-id', theme.id)
        .attr('data-theme-url', theme.url)
        .attr('src', theme.imageSrc)
        .attr('title', theme.title);
    },

    selectTheme: function(element) {
      $('.theme-selected', $themeSelectionArea).removeClass('theme-selected');
      $(element).addClass('theme-selected');
    },
    
    selectInvertTheme: function() {
      var themeId = $thumbnail.attr('data-theme-id');
      var $selectedTheme = $('li[data-theme-id="' + themeId + '"]',
        $themeSelectionArea);
      st.selectTheme($selectedTheme);

      // Scroll selected theme element into theme selection view.
      var themeChangeBody = $id('theme-change-body');
      try {
        themeChangeBody.scrollTop = $selectedTheme.get().offsetTop -
          themeChangeBody.offsetTop;
      } catch (e){}

    },

    applyTheme: function(themeName) {
      var themeId = 'custom';
      var themeImage = '';
      var themeUrl = '';

      // If the theme is candidate theme, reset themeId.
      for (var tmpThemeId in themes) {
        if (themes[tmpThemeId].name == themeName ||
            themes[tmpThemeId].installedName == themeName) {
          themeId = tmpThemeId;
          break;
        }
      }

      if (themeId != 'custom') {
        themeUrl = st.constructThemeUrl(themes[themeId].urlId);
      }
      themeImage = st.constructThemeImgUrl(themeId);
      st.setThemeData({
        id: themeId,
        url: themeUrl,
        imageSrc: themeImage,
        title: themeName
      });
    }
  };
})();